const router = require('koa-router')()
const User = require('../dbs/modules/user')
const jwt = require('jsonwebtoken')

router.prefix('/user')

// 注册
router.post('/register', async (ctx, next) => {
    let {
        user,
        pass,
        check,
        email,
        iphone
    } = ctx.request.body
    let msg, code;
    if (user.length <= 0 || user == "") {
        msg = "用户名不能为空"
        code = -1
    } else if (pass.length < 6) {
        msg = "密码格式错误"
        code = -1
    } else if (check != pass) {
        msg = "两次密码不一致"
        code = -1
    } else if (email.length <= 0 || email == "") {
        msg = "邮箱格式错误"
        code = -1
    } else if (iphone.length < 11) {
        msg = "请输入正确的手机号"
        code = -1
    }
    // 是否被注册
    let checkUser = await User.findOne({
        user
    })
    if (checkUser != null) {
        ctx.body = {
            success: false,
            code: -1,
            msg: '该账号已被注册'
        }
        return false
    }
    // 新增账号
    let addUser = new User({
        user: user,
        pass: pass,
        check: check,
        email: email,
        iphone: iphone,
        timeStamp: new Date().toLocaleString()
    })

    try {
        await addUser.save()
        code = 0
    } catch (error) {
        code = -1
    }
    ctx.body = {
        msg,
        success: true,
        code
    }
})

// 登录
router.post('/login', async (ctx, next) => {
    let {
        username,
        password
    } = ctx.request.body
    let msg, code, success
    let user = await User.find({
        "user": username
    })
    // 校验用户是否存在
    if(user.length == 0) {
      ctx.body = {
          success: false,
          code: -1,
          msg: '用户不存在！'
      }
      return;
    }
    // 校验账号密码
    if (username === user[0].user && password === user[0].pass) {
      let secret = Math.random() * 100 + '1'
      let token = jwt.sign(user[0].user, secret)
      let userInfo = {
        userName: user[0].user,
        email: user[0].email,
        token
      }
      ctx.body = {
          success: true,
          code: 0,
          msg: '登录成功！',
          userInfo
      }
    } else {
      ctx.body = {
          success: false,
          code: -1,
          msg: '密码错误！'
      }
    }
})

module.exports = router
